package com.jhd.jiangxi.activity.scan.remove;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.android.material.tabs.TabLayout;
import com.jhd.jiangxi.R;
import com.jhd.jiangxi.UtilHelper;
import com.jhd.jiangxi.activity.main.BaseActivity;
import com.jhd.jiangxi.activity.scan.BillFragment;
import com.jhd.jiangxi.activity.scan.ContentFragment;
import com.jhd.jiangxi.entity.LastInputEditText;
import com.jhd.jiangxi.service.VaccineService;
import com.jhd.jiangxi.util.DeptChoose;
import com.jhd.jiangxi.util.EditTextDel;
import com.jhd.jiangxi.util.PopWindow;
import com.jhd.jiangxi.service.GetVaccineService;
import com.jhd.jiangxi.util.ScanUtil;
import com.jhd.jiangxi.vo.ElectCodePackageVoList;
import com.jhd.jiangxi.vo.JsonForResult;
import com.jhd.jiangxi.vo.PiatsInfo;
import com.jhd.jiangxi.vo.RefDept;
import com.jhd.jiangxi.vo.RemoveOrderDtlVo;
import com.jhd.jiangxi.vo.RemoveOrderMstVo;
import com.jhd.jiangxi.vo.StorageInfo;
import com.jhd.jiangxi.vo.VaccineBalance;
import com.jhd.jiangxi.vo.VaccineCount;

import net.zigin.commons.util.StringUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/*移库*/
public class RemoveActivity extends BaseActivity implements View.OnClickListener {

    private ViewPager vp;
    private BillFragment billFragment;
    private ContentFragment contentFragment;
    private List<Fragment> mDatas = new ArrayList<Fragment>();
    private TabLayout tabs;
    private String[] moveTypeName = {"报废移库", "转储移库"};
    private String[] moveTypeId = {"1", "0"};
    private String[] moveReasonName = {"包装无法识别", "超过有效期", "不符合储存温度要求", "其他"};
    private String[] moveReasonId = {"01", "02", "03", "09"};
    private FragmentPagerAdapter adapter;
    private BarcodeDataReceiver barcodeDataReceiver;
    private AlertDialog _alertDialog = null;
    private final List<String> id = new ArrayList<String>();
    private final List<String> name = new ArrayList<String>();
    List<VaccineCount> vaccineCountList = new ArrayList<>();
    private RecyclerView rvVaccine;
    private Context context = RemoveActivity.this;
    private TextView btnSourceType_0, btnType, btnApprovalIn, btnOutDept, btnVaccineType, btnPriceBook, btnToTemp, btnStorage;//bill界面:审批人,供货单位,疫苗类型,价格本,下一步
    private Button btnSubmitVaccine, btnDelAllVaccine, btnCountVaccine;//content界面:提交,清空,入库明细
    public static List<VaccineBalance> vaccineBalanceList = new ArrayList<>();
    private ListView listView;
    private PopupWindow popup;private boolean isCheck=false;
    protected RecyclerAdapter moveRecyclerAdapter;
    List<String> storageName = new ArrayList<>();
    List<String> storageId = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remove);
        popup = new PopupWindow(context);
        checkAllScrapOrderByCondition();
        checkAllPickOrderByCondition();
        openScan(context);
        initView();
        initEvent();
    }

    /*将顶部标题带入,新建俩个fragment*/
    private void initView() {
        initHeader("移库");
        vp = (ViewPager) findViewById(R.id.vpSheet);
        billFragment = new BillFragment();
        contentFragment = new ContentFragment();
        mDatas.add(billFragment);
        mDatas.add(contentFragment);
        tabs = findViewById(R.id.tabSheet);
    }

    @Override
    public void fragmentCreated(View view) {
        super.fragmentCreated(view);
        btnSourceType_0 = (TextView) view.findViewById(R.id.btnSourceType_0);
        btnSourceType_0.setVisibility(View.GONE);
        btnApprovalIn = (TextView) view.findViewById(R.id.btnApprovalIn);
        btnPriceBook = (TextView) view.findViewById(R.id.btnPriceBook);
        btnToTemp = (TextView) view.findViewById(R.id.btnToTemp);
        btnType = (TextView) view.findViewById(R.id.btnType);
        btnType.setText("移库类型");
        btnType.setVisibility(View.VISIBLE);
        btnOutDept = (TextView) view.findViewById(R.id.btnOutDept);
        btnOutDept.setVisibility(View.GONE);
        btnVaccineType = (TextView) view.findViewById(R.id.btnVaccineType);
        btnVaccineType.setVisibility(View.GONE);
        btnStorage = (TextView) view.findViewById(R.id.btnStorage);
        btnStorage.setVisibility(View.GONE);
        btnApprovalIn.setOnClickListener((View.OnClickListener) context);
        btnType.setOnClickListener((View.OnClickListener) context);
        btnPriceBook.setOnClickListener((View.OnClickListener) context);
        btnToTemp.setOnClickListener((View.OnClickListener) context);
        getApproval(btnApprovalIn, "移库");//获取审批人列表
        getDept();//获取供货单位列表
        getPriceBookMst();//获取价格本列表
        //getStorageInfoList();//获取储位列表
    }

    @Override
    public void fragmentCreated2(View view) {
        super.fragmentCreated2(view);
        btnSubmitVaccine = (Button) view.findViewById(R.id.btnSubmitVaccine);
        btnDelAllVaccine = (Button) view.findViewById(R.id.btnDelAllVaccine);
        btnCountVaccine = (Button) view.findViewById(R.id.btnCountVaccine);
        rvVaccine = (RecyclerView) view.findViewById(R.id.rvVaccine);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        rvVaccine.setLayoutManager(layoutManager);
        btnSubmitVaccine.setOnClickListener((View.OnClickListener) context);
        btnDelAllVaccine.setOnClickListener((View.OnClickListener) context);
        btnCountVaccine.setOnClickListener((View.OnClickListener) context);
    }

    /*点击下一步或者点击扫码入库之前的判断*/
    private void setBtnToTemp() {
        if (btnApprovalIn.getText().toString().equals("审核人") || btnType.getText().toString().equals("移库类型") || btnPriceBook.getText().toString().equals("价格本")) {
            UtilHelper.alertMsg(context, "请配置好单据页面", "点击任意处关闭弹窗");
            vp.setCurrentItem(0);
        } else {
            if(isPick&&isScrap){
                String checkType=btnType.getText().toString();
                if(checkType.equals(application.getCheckType())){
                    vp.setCurrentItem(1);
                    if (btnType.getText().toString().equals("报废移库")) {
                        storageInfoList=null;
                        getStorageInfoByDept("2");
                    } else if (btnType.getText().toString().equals("转储移库")) {
                        storageInfoList=null;
                        getStorageInfoByDept("1");
                    }
                    ScanUtil.powerOnScan(context);
                }else{
                    if(vaccineBalanceList.size()>0){
                        vp.setCurrentItem(0);
                        isClearDialog();
                    }else {
                        application.setCheckType(btnType.getText().toString());
                        if (btnType.getText().toString().equals("报废移库")) {
                            storageInfoList=null;
                            getStorageInfoByDept("2");
                        } else if (btnType.getText().toString().equals("转储移库")) {
                            storageInfoList=null;
                            getStorageInfoByDept("1");
                        }
                        ScanUtil.powerOnScan(context);

                    }
                }
            }else{
                vp.setCurrentItem(0);
                Toast.makeText(context,"没有移库权限!",Toast.LENGTH_SHORT).show();
            }
        }
    }
    public void isClearDialog() {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
        alertBuilder.setTitle("移库");
        alertBuilder.setMessage("移库类型已经重新选过,将会对之前的扫描进行清空，您确定吗?");
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                application.setCheckType(btnType.getText().toString());
                vaccineBalanceList.clear();
                moveRecyclerAdapter = new RecyclerAdapter(vaccineBalanceList);
                rvVaccine.setAdapter(moveRecyclerAdapter);
                vp.setCurrentItem(1);
                ScanUtil.powerOnScan(context);
                _alertDialog.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                _alertDialog.dismiss();
            }
        });
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
    }

    private void initEvent() {
        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
//                添加选中Tab的逻辑
                if (tab.getPosition() == 1) {
                    setBtnToTemp();
                } else {
                    ScanUtil.powerOffScan(context);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
//                添加未选中Tab的逻辑
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
//                再次选中tab的逻辑
            }
        });
        adapter = new FragmentPagerAdapter(getSupportFragmentManager(), 1) {
            @Override
            public int getCount() {
                return mDatas.size();
            }

            @Override
            public Fragment getItem(int position) {
                return mDatas.get(position);
            }
        };
        vp.setAdapter(adapter);
        tabs.setupWithViewPager(vp);
        TabLayout.Tab tab = tabs.getTabAt(0);
        ((View) tab.view).setBackgroundResource(R.drawable.tab_left);
        tab.setText("交货单");
        tab = tabs.getTabAt(1);
        ((View) tab.view).setBackgroundResource(R.drawable.tab_right);
        tab.setText("扫码移库");
    }

    public void openScan(Context context) {
        barcodeDataReceiver = new BarcodeDataReceiver();
        IntentFilter mFilter = new IntentFilter("nlscan.action.SCANNER_RESULT");
        context.registerReceiver(barcodeDataReceiver, mFilter);
        Intent mIntent = new Intent("ACTION_BAR_SCANCFG");
        mIntent.putExtra("SCAN_INTERVAL", Long.valueOf(3000));
        mIntent.putExtra("EXTRA_TRIG_MODE", 0);//连续扫描
        mIntent.putExtra("EXTRA_SCAN_MODE", 3);//广播输出模式
        context.sendBroadcast(mIntent);
        Intent mIntent2 = new Intent("ACTION_BAR_SCANCFG");
        mIntent2.putExtra("EXTRA_SCAN_NOTY_SND", 1);
        mIntent2.putExtra("EXTRA_SCAN_NOTY_VIB", 1);
        sendBroadcast(mIntent2);
    }

    public void closeScan(Context context) {
        context.unregisterReceiver(barcodeDataReceiver);
    }

    class BarcodeDataReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String scanResult_1 = intent.getStringExtra("SCAN_BARCODE1");
            final String scanStatus = intent.getStringExtra("SCAN_STATE");
            if ("ok".equals(scanStatus)) {
                ScanUtil.stopScan(context);
                if (!contains(vaccineBalanceList, scanResult_1)) {
                    Intent mIntent2 = new Intent("ACTION_BAR_SCANCFG");
                    mIntent2.putExtra("EXTRA_SCAN_POWER", 0);
                    sendBroadcast(mIntent2);
                    getCodeBalanceByCode(scanResult_1);
                } else {
                    Toast.makeText(context, "该码已经扫描过", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    public boolean contains(List<VaccineBalance> vaccineBalanceList, String code) {
        for (VaccineBalance infoScrap : vaccineBalanceList) {
            if (infoScrap.getCode().equals(code)) {
                return true;
            }
        }
        return false;
    }

    /*重写返回键*/
    private void back() {
        if (vp.getCurrentItem() == 0) {
            onBackPressed();
        } else if (vp.getCurrentItem() == 1) {
            vp.setCurrentItem(0);//如果是在内容界面点击返回,就回到单据界面
        }
    }

    /*头部的方法,因为返回的功能要重新编写,所以直接重写*/
    protected void initHeader(String title) {
        if ("0".equals(application.getBackSystem())) title = title + "(测试版本)";
        TextView tvTitle = ((TextView) findViewById(R.id.screenTitle));
        if (tvTitle != null) tvTitle.setText(title);
        findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back();
            }
        });
        String userName = application.getRealName() == null ? application.getUserName() : application.getRealName();
        ((TextView) findViewById(R.id.tvHeaderUserName)).setText(userName);
    }

    /*重写返回方法,和initHeader一样*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void saveRemoveOrderMstAndDtl() {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        RemoveOrderMstVo removeOrderMstVo = new RemoveOrderMstVo();
        removeOrderMstVo.setApprovalId(application.getApprovalId());
        removeOrderMstVo.setPriceBookNo(application.getPriceNoIn());
        removeOrderMstVo.setPriceBookMstId(application.getPriceBookMstId());
        if (btnType.getText().toString().equals("报废移库")) {
            removeOrderMstVo.setSourceType(1);
        } else if (btnType.getText().toString().equals("转储移库")) {
            removeOrderMstVo.setSourceType(0);
        }
        if (application.getRemark() == null) {
            removeOrderMstVo.setRemark("");//备注
        } else {
            removeOrderMstVo.setRemark(application.getRemark());//备注
        }
        List<RemoveOrderDtlVo> removeOrderDtlVoList = new ArrayList<RemoveOrderDtlVo>();
        for (VaccineBalance vaccineBalance : vaccineBalanceList) {
            RemoveOrderDtlVo removeOrderDtlVo = new RemoveOrderDtlVo();
            removeOrderDtlVo.setCategory(vaccineBalance.getCategory());
            ElectCodePackageVoList electCodePackageVoList = new ElectCodePackageVoList();
            electCodePackageVoList.setCodeLevel(vaccineBalance.getCodeLevel());
            electCodePackageVoList.setElectCode(vaccineBalance.getCode());
            electCodePackageVoList.setQuantity(vaccineBalance.getInQuantity());
            removeOrderDtlVo.setElectCodePackageVoList(electCodePackageVoList);
            removeOrderDtlVo.setExpiryDate(vaccineBalance.getExpiryDate());
            removeOrderDtlVo.setLotNumber(vaccineBalance.getLotNumber());
            removeOrderDtlVo.setManufacturerId(vaccineBalance.getManufacturerId());
            removeOrderDtlVo.setManufacturerName(vaccineBalance.getManufacturerName());
            removeOrderDtlVo.setPropertyId(vaccineBalance.getPropertyId());
            removeOrderDtlVo.setQuantity(Integer.valueOf(vaccineBalance.getInQuantity()));
            removeOrderDtlVo.setRemark(vaccineBalance.getRemark());
            removeOrderDtlVo.setSourceStorage(vaccineBalance.getStorageCodeVoList().get(0).getStorageName());
            removeOrderDtlVo.setSourceStorageId(vaccineBalance.getStorageCodeVoList().get(0).getStorageId());
            removeOrderDtlVo.setTargetStorage(vaccineBalance.getTargetStorage());
            removeOrderDtlVo.setTargetStorageId(vaccineBalance.getTargetStorageId());
            removeOrderDtlVo.setVaccineDose(vaccineBalance.getVaccineDose());
            removeOrderDtlVo.setVaccineId(vaccineBalance.getVaccineId());
            removeOrderDtlVo.setVaccineLotsId(vaccineBalance.getVaccineLotsId());
            removeOrderDtlVo.setVaccineName(vaccineBalance.getVaccineName());
            removeOrderDtlVo.setVaccineSpec(vaccineBalance.getVaccineSpec());
            removeOrderDtlVoList.add(removeOrderDtlVo);
        }
        for (int i = 0; i < vaccineBalanceList.size(); i++) {

        }
        params.put("deptId", application.getDeptId());
        params.put("userId", application.getUserId());
        params.put("removeOrderDtlVoList", removeOrderDtlVoList);
        params.put("removeOrderMstVo", removeOrderMstVo);
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        GetVaccineService vs = retrofit.create(GetVaccineService.class);
        String token = application.getAccessToken();
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
        Call<JsonForResult> jsonForResultCall = vs.saveRemoveOrderMstAndDtl(token, requestBody);
        jsonForResultCall.enqueue(new saveRemoveOrderMstAndDtl());
    }

    private class saveRemoveOrderMstAndDtl implements Callback<JsonForResult> {

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    Toast.makeText(context, "移库成功", Toast.LENGTH_SHORT).show();
                    onBackPressed();
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(context, "错误", msg);
        }
    }

    /*button的点击监听*/
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnToTemp:
                vp.setCurrentItem(1);
                break;
            case R.id.btnApprovalIn://bill界面点击选择审批人
                name.clear();
                id.clear();
                if(approvalList!=null){
                    for (int i = 0; i < approvalList.size(); i++) {
                        name.add(approvalList.get(i).getUserName1());
                        id.add(approvalList.get(i).getId());
                    }
                    PopWindow.show(application, context,popup,isCheck, (TextView) v, name, id, 0);
                }else{
                    Toast.makeText(context,"未获取审批人信息,请稍后重试!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnType://bill界面点击选择移库类型btnRemoveType
                v.setBackgroundResource(R.drawable.selector_focused);
                PopWindow.show(application, context,popup,isCheck, (TextView) v, Arrays.asList(moveTypeName), Arrays.asList(moveTypeId), 5);
                break;
            case R.id.btnPriceBook://bill界面点击选择价格本
                name.clear();
                id.clear();
                if(priceBook!=null){
                    for (int i = 0; i < priceBook.size(); i++) {
                        name.add(priceBook.get(i).getPriceBookNo());
                        id.add(priceBook.get(i).getId());
                    }
                    PopWindow.show(application,context,popup,isCheck,(TextView) v,name,id,3);
                }else{
                    Toast.makeText(context,"未获取价格本信息,请稍后重试!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnSubmitVaccine://content界面点击保存扫描疫苗
                showDialog(1, v, "确认提交");
                break;
            case R.id.btnDelAllVaccine://content界面点击删除所有扫到的疫苗
                showDialog(2, v, "清空扫描");
                break;
            case R.id.btnCountVaccine://content界面点击跳转到汇总界面
                startActivity(new Intent(context, RemoveDetailActivity.class));
                break;
        }
    }

    public void showDialog(int dex, View v, String title) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(v.getContext());
        alertBuilder.setTitle(title);
        if (title.equals("确认提交")) {
            String msg = "";
            vaccineCountList.clear();
            for (VaccineBalance vaccineBalance : vaccineBalanceList) {
                VaccineCount vaccineCount = new VaccineCount();
                vaccineCount.setName(vaccineBalance.getVaccineName());
                if (!vaccineCountList.contains(vaccineCount)) {
                    vaccineCountList.add(vaccineCount);
                }
            }
            for (VaccineCount vaccineCount : vaccineCountList) {
                int num = 0;
                for (VaccineBalance vaccineBalance : vaccineBalanceList) {
                    if (vaccineBalance.getVaccineName().equals(vaccineCount.getName())) {
                        num = num + Integer.valueOf(vaccineBalance.getInQuantity());
                    }
                }
                vaccineCount.setNum(num);
            }
            for (int i = 0; i < vaccineCountList.size(); i++) {
                msg = msg + "疫苗名称:" + vaccineCountList.get(i).getName() + " 扫码数:" + vaccineCountList.get(i).getNum() + "\n";
            }
            alertBuilder.setMessage("已扫疫苗 " + msg + "你确定移库吗?");
        } else if (title.equals("清空扫描")) {
            alertBuilder.setIcon(R.mipmap.dialog_alert);
            alertBuilder.setMessage("你确定清空所有扫描疫苗吗");
        }
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (dex == 1) {//保存所有数据
                    saveRemoveOrderMstAndDtl();
                } else if (dex == 2) {//清空储位数据
                    vaccineBalanceList.clear();
                    moveRecyclerAdapter = new RecyclerAdapter(vaccineBalanceList);
                    rvVaccine.setAdapter(moveRecyclerAdapter);
                }
                _alertDialog.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                _alertDialog.dismiss();
            }
        });
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
    }

    public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
        private List<VaccineBalance> vaccineBalanceList;

        public RecyclerAdapter(List<VaccineBalance> vaccineBalanceList) {
            this.vaccineBalanceList = vaccineBalanceList;
        }

        @NonNull
        @Override
        public RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_vaccine_move, parent, false);
            RecyclerAdapter.ViewHolder viewHolder = new RecyclerAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerAdapter.ViewHolder holder, int position) {
            holder.tv_electCode.setText(vaccineBalanceList.get(position).getCode());
            holder.tvVaccineName.setText(vaccineBalanceList.get(position).getVaccineName());
            holder.tvFactory.setText(vaccineBalanceList.get(position).getManufacturerName());
            holder.tvApprovalNo.setText(vaccineBalanceList.get(position).getLotNumber());
            holder.tvVaccineDose.setText(vaccineBalanceList.get(position).getVaccineDose() + "/" + vaccineBalanceList.get(position).getVaccineSpec());
            holder.tvCodeLevelStr.setText(vaccineBalanceList.get(position).getCodeLevelStr());
            holder.tvExpireDate.setText(vaccineBalanceList.get(position).getExpiryDate());
            holder.tvStorage.setText(vaccineBalanceList.get(position).getTargetStorage());
            holder.tvPersonQuantity.setText(vaccineBalanceList.get(position).getInQuantity());
            holder.tvReason.setText(vaccineBalanceList.get(position).getRemark());
            holder.tvStorageCount.setText(String.valueOf(vaccineBalanceList.get(position).getQuantity()));
            if (vaccineBalanceList.get(position).getCategory().equals("1")) {
                holder.iv_category.setText("免规");
            }else if(vaccineBalanceList.get(position).getCategory().equals("4")){
                holder.iv_category.setText("地方免规");
            }else if(vaccineBalanceList.get(position).getCategory().equals("5")){
                holder.iv_category.setText("应急");
            }else if(vaccineBalanceList.get(position).getCategory().equals("2")){
                holder.iv_category.setText("非免规");
            }else if(vaccineBalanceList.get(position).getCategory().equals("6")){
                holder.iv_category.setText("群体性预防");
            }else if(vaccineBalanceList.get(position).getCategory().equals("7")){
                holder.iv_category.setText("紧急");
            }
            holder.tvPersonQuantity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            holder.iv_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    vaccineBalanceList.remove(position);
                    notifyItemRemoved(position);//移除该位置的项目
                    notifyItemRangeChanged(position, getItemCount() - position);//局部刷新从该position位置开始到剩余的所有项目
                }
            });
            //跳弹窗,选择储位
            holder.linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialogShow(vaccineBalanceList.get(position), position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return vaccineBalanceList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_electCode, tvVaccineName, tvFactory, tvApprovalNo, tvStorageCount, tvReason,iv_category; //追溯码,疫苗名称，生产厂家，批号,库存,原因
            TextView tvVaccineDose, tvCodeLevelStr, tvExpireDate, tvStorage, tvPersonQuantity; // 计量规格,包装类型,效期,储位
            ImageView iv_del;
            LinearLayout linearLayout;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_electCode = itemView.findViewById(R.id.tv_electCode);
                this.tvVaccineName = itemView.findViewById(R.id.tvVaccineName);
                this.iv_del = itemView.findViewById(R.id.iv_del);
                this.iv_category = itemView.findViewById(R.id.iv_category);
                this.tvFactory = itemView.findViewById(R.id.tvFactory);
                this.tvApprovalNo = itemView.findViewById(R.id.tvApprovalNo);
                this.tvVaccineDose = itemView.findViewById(R.id.tvVaccineDose);
                this.tvCodeLevelStr = itemView.findViewById(R.id.tvCodeLevelStr);
                this.tvExpireDate = itemView.findViewById(R.id.tvExpireDate);
                this.tvStorageCount = itemView.findViewById(R.id.tvStorageCount);
                this.tvStorage = itemView.findViewById(R.id.tvStorage);
                this.tvReason = itemView.findViewById(R.id.tvReason);
                this.tvPersonQuantity = itemView.findViewById(R.id.tvPersonQuantity);
                this.linearLayout = itemView.findViewById(R.id.linearLayout);
            }
        }
    }

    /*弹窗*/
    public void dialogShow(VaccineBalance vaccineBalance, int position) {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_move, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
        TextView btnReStorage = (TextView) view.findViewById(R.id.btnReStorage);
        TextView tvVaccineName = (TextView) view.findViewById(R.id.tvVaccineName);
        btnReStorage.setText(vaccineBalance.getStorageCodeVoList().get(0).getStorageName());
        tvVaccineName.setText(vaccineBalance.getVaccineName());
        LastInputEditText btnTargetStorage = (LastInputEditText) view.findViewById(R.id.btnTargetStorage);
        TextView btnLossNumber = (EditText) view.findViewById(R.id.btnLossNumber);
        if(vaccineBalance.getInQuantity()!=null){
            btnLossNumber.setText(vaccineBalance.getInQuantity());
        }else{
            btnLossNumber.setText(vaccineBalance.getPkgAmount());
        }
        if(vaccineBalance.getTargetStorage()!=null){
            btnTargetStorage.setTextColor(getResources().getColor(R.color.billTextChoose));
            btnTargetStorage.setText(vaccineBalance.getTargetStorage());
        }
        btnTargetStorage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                storageName.clear();storageId.clear();
                if(storageInfoList!=null&&isCheck==false){
                    for (StorageInfo storageInfo : storageInfoList) {
                        if(storageInfo.getName().contains(btnTargetStorage.getText().toString())){
                            storageName.add(storageInfo.getName());
                            storageId.add(storageInfo.getId());
                        }
                    }
                    show(vaccineBalance,btnTargetStorage, storageName, storageId);
                }
            }
        });
        btnTargetStorage.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN){
                    if (storageInfoList != null) {
                        storageName.clear();storageId.clear();
                        for (StorageInfo storageInfo : storageInfoList) {
                            if(storageInfo.getName().contains(btnTargetStorage.getText().toString())) {
                                storageName.add(storageInfo.getName());
                                storageId.add(storageInfo.getId());
                            }
                        }
                        show(vaccineBalance,btnTargetStorage, storageName, storageId);
                    }else{
                        Toast.makeText(context, "目标储位为空!", Toast.LENGTH_SHORT).show();
                    }
                }
                return false;
            }
        });
        if (btnType.getText().toString().equals("报废移库")) {
            TextView btnReason = (TextView) view.findViewById(R.id.btnReason);
            btnReason.setVisibility(View.VISIBLE);
            if(vaccineBalance.getRemark()!=null)btnReason.setText(vaccineBalance.getRemark());
            btnReason.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    show(null,btnReason, Arrays.asList(moveReasonName), Arrays.asList(moveReasonId));
                }
            });
        } else if (btnType.getText().toString().equals("转储移库")) {
            EditText btnReason = (EditText) view.findViewById(R.id.btnReason2);
            btnReason.setVisibility(View.VISIBLE);
            if(vaccineBalance.getRemark()!=null)btnReason.setText(vaccineBalance.getRemark());
        }
        TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tvConfirm);
        btnReStorage.setText(vaccineBalance.getStorageCodeVoList().get(0).getStorageName());//默认是选中第一个储位,记得把储位的id留着
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent("ACTION_BAR_SCANCFG");
                mIntent.putExtra("EXTRA_SCAN_POWER", 1);//禁用扫描功能
                sendBroadcast(mIntent);
                _alertDialog.dismiss();
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent("ACTION_BAR_SCANCFG");
                mIntent.putExtra("EXTRA_SCAN_POWER", 1);//禁用扫描功能
                sendBroadcast(mIntent);
                if (btnTargetStorage.getText().toString().equals("")) {
                    Toast.makeText(context, "请选择目标储位!", Toast.LENGTH_SHORT).show();
                }else if(!DeptChoose.isStorageContain(storageInfoList,btnTargetStorage.getText().toString())){
                    Toast.makeText(context, "请选择正确的目标储位!", Toast.LENGTH_SHORT).show();
                } else {
                    if (!btnLossNumber.getText().toString().trim().equals("") && Integer.valueOf(btnLossNumber.getText().toString().trim()) > 0
                            &&Integer.valueOf(btnLossNumber.getText().toString().trim())<=Integer.valueOf(vaccineBalance.getPkgAmount())) {
                        _alertDialog.dismiss();
                        vaccineBalance.setInQuantity(btnLossNumber.getText().toString().trim());
                        if (btnType.getText().toString().equals("报废移库")) {
                            TextView btnReason = (TextView) view.findViewById(R.id.btnReason);
                            vaccineBalance.setRemark(btnReason.getText().toString());
                        } else if (btnType.getText().toString().equals("转储移库")) {
                            EditText btnReason = (EditText) view.findViewById(R.id.btnReason2);
                            vaccineBalance.setRemark(btnReason.getText().toString());
                        }
                        if (position == vaccineBalanceList.size()) {
                            vaccineBalanceList.add(vaccineBalance);
                            if (vaccineBalanceList.size() == 1) {
                                moveRecyclerAdapter = new RecyclerAdapter(vaccineBalanceList);
                                rvVaccine.setAdapter(moveRecyclerAdapter);
                            } else {
                                moveRecyclerAdapter.notifyItemRangeChanged(position, 1);//更新的位置,更新的总条数
                            }
                        } else {
                            moveRecyclerAdapter.notifyItemRangeChanged(position, 1);//更新的位置,更新的总条数
                        }
                    } else {
                        Toast.makeText(context, "移库数量不正确,请重新输入!", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

    }

    private void show(VaccineBalance vaccineBalance,TextView textView, List<String> name, List<String> id) {
        isCheck=false;
        listView = new ListView(context);
        listView.setDivider(null);//设置分割线
        listView.setVerticalScrollBarEnabled(false);//不显示滑动条
        listView.setAdapter(new MyAdapter(vaccineBalance,textView, name, id));
        if(popup.isShowing())popup.dismiss();
        popup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        popup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popup.setWidth(textView.getWidth());
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.selector_unfocused));
        popup.setContentView(listView);//设置显示内容
        popup.setOutsideTouchable(true);//点击PopupWindow以外的区域自动关闭该窗口
        popup.showAsDropDown(textView, 0, 5);//显示在edit控件的下面0,0代表偏移量
        textView.setBackgroundResource(R.drawable.selector_focused);
        if(name.size()>0){
            popup.setOutsideTouchable(false);//点击PopupWindow以外的区域自动关闭该窗口
        }
        popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                textView.setBackgroundResource(R.drawable.selector_unfocused);
            }
        });
    }

    //适配器
    private class MyAdapter extends BaseAdapter {
        private List<String> name, id;
        private TextView textView;
        private VaccineBalance vaccineBalance;

        public MyAdapter(VaccineBalance vaccineBalance,TextView textView, List<String> name, List<String> id) {
            this.name = name;
            this.id = id;
            this.textView = textView;
            this.vaccineBalance = vaccineBalance;
        }

        @Override
        public int getCount() {
            return name.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HolderView holderView = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.item_dialog_login, null);
                holderView = new HolderView();
                holderView.text = (TextView) convertView.findViewById(R.id.tvStorage);
                convertView.setTag(holderView);
            } else {
                holderView = (HolderView) convertView.getTag();
            }

            holderView.text.setText(name.get(position));

            holderView.text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isCheck=true;
                    notifyDataSetChanged();
                    textView.setBackgroundResource(R.drawable.selector_unfocused);
                    if(vaccineBalance!=null){
                        vaccineBalance.setTargetStorageId(id.get(position));
                        vaccineBalance.setTargetStorage(name.get(position));
                        EditTextDel.setCanDel((LastInputEditText) textView,false);
                    }
                    textView.setText(name.get(position));
                    textView.setTextColor(getResources().getColor(R.color.billTextChoose));
                    popup.dismiss();
                }
            });
            return convertView;
        }
    }

    public class HolderView {//由于这里用户都是同一个人,就省略用户图像的刷新
        private TextView text;
    }

    protected void getCodeBalanceByCode(String code) {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("deptId", application.getDeptId());
        params.put("code", code);
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getCodeBalanceByCode(token, params);
        jsonForResultCall.enqueue(new getVaccineInfoByCodeSingleCallback());//根据index来判断储位要不要从新选择
    }

    private class getVaccineInfoByCodeSingleCallback implements Callback<JsonForResult> {
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    System.out.println("是否" + (!jsonForResult.isSuccess()));
                    if (jsonForResult.getData() == null) {
                        UtilHelper.alertMsg(getApplicationContext(), "错误", jsonForResult.getMessage());
                        return;
                    }
                    //请求授权信息
                    VaccineBalance vaccineBalance = JSON.parseObject(jsonForResult.getData().toString(), VaccineBalance.class);
                    dialogShow(vaccineBalance, vaccineBalanceList.size());
                } else if (jsonForResult != null && (!jsonForResult.isSuccess())) {
                    Toast.makeText(getApplicationContext(), jsonForResult.getMessage(), Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(getApplicationContext(), "错误", msg);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeScan(context);vaccineBalanceList.clear();
        application.clearBill();
    }
}